package dao

import (
	"fmt"
	__ "user-srv/basic/proto"
	"user-srv/handler/models"
)

// 勋章添加
func UserBadgesAdd(in *__.UserBadgesAddReq) (*models.UserBadges, error) {
	var userBadges models.UserBadges
	var user models.User
	err := user.GetUserInfoById(int(in.UserId))
	if err != nil {
		return nil, fmt.Errorf("用户查找失败")
	}
	if user.Id == 0 {
		return nil, fmt.Errorf("用户不存在")
	}

	userBadges.UserId = in.UserId // 用户id

	var badgeRules models.BadgeRules
	err = badgeRules.GetBadgeRulesInfoById(int(in.RulesId))
	if err != nil {
		return nil, fmt.Errorf("勋章规则查找失败")
	}
	if badgeRules.Id == 0 {
		return nil, fmt.Errorf("勋章规则不存在")
	}

	// 检查用户是否已获得该勋章
	find, err := userBadges.UserBadgesFind()
	if err != nil {
		return nil, fmt.Errorf("用户勋章查找失败")
	}
	for _, ub := range find {
		if ub.RulesId == in.RulesId {
			return nil, fmt.Errorf("用户已获得该勋章")
		}
	}

	userBadges.RulesId = in.RulesId // 勋章规则id

	err = userBadges.UserBadgesAdd()
	if err != nil {
		return nil, fmt.Errorf("用户勋章添加失败")
	}

	return &userBadges, nil
}

// 勋章展示
func UserBadgesFind(in *__.UserBadgesFindReq) ([]*__.UserBadgesFind, error) {
	var userBadges models.UserBadges
	var userBadgesFind []*__.UserBadgesFind

	find, err := userBadges.UserBadgesFind()
	if err != nil {
		return nil, fmt.Errorf("用户会员展示查找失败")
	}

	for _, ub := range find {
		userBadgesFind = append(userBadgesFind, &__.UserBadgesFind{
			UserId:     ub.UserId,
			RulesId:    ub.RulesId,
			ObtainedAt: ub.ObtainedAt.Format("2006-01-02 15:04:05"),
			Status:     uint64(ub.Status),
		})
	}
	return userBadgesFind, nil
}
